import React, { Component, createRef } from 'react'
import style from './index.module.scss'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Input,
  Radio,
  Upload,
  Modal,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import Channel from 'components/Channel'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { baseURL } from 'utils/request'
import { addArticle, getArticleInfo, editArticle } from 'api/article'
export default class index extends Component {
  state = {
    // 文章封面类型
    type: 0,
    // 上传图片的显示
    fileList: [],
    // 预览框显示状态
    showPreview: false,
    // 预览图片
    PreviewUrl: '',
    // 根据id判断是修改文章还是新增文章
    id: this.props.match.params.id,
  }
  formRef = React.createRef()
  render() {
    return (
      <div className={style.root}>
        <Card
          // 头部
          title={
            // 面包屑
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {this.state.id ? '编辑文章' : '发布文章'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            labelCol={{ span: 4 }}
            size="large"
            onFinish={this.onFinish}
            validateTrigger={['onBlur', 'onChange']}
            initialValues={{
              content: '',
              type: this.state.type,
            }}
            ref={this.formRef}
          >
            {/* 文章标题 */}
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '文章标题不能为空' }]}
            >
              <Input
                style={{ width: 400 }}
                placeholder="请输入文章标题"
              ></Input>
            </Form.Item>
            {/* 频道下拉列表 */}
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择频道' }]}
            >
              <Channel></Channel>
            </Form.Item>
            {/* 封面 */}
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.changeType}>
                <Radio value={0}>无图</Radio>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
              </Radio.Group>
            </Form.Item>
            {/* 上传组件 */}
            <Form.Item wrapperCol={{ offset: 4 }}>
              {this.state.type !== 0 && (
                <Upload
                  listType="picture-card"
                  fileList={this.state.fileList}
                  action={`${baseURL}upload`}
                  name="image"
                  onChange={this.UploadImage}
                  onPreview={this.handlePreview}
                  beforeUpload={this.beforeUpload}
                >
                  {this.state.fileList.length < this.state.type && (
                    <PlusOutlined />
                  )}
                </Upload>
              )}
            </Form.Item>
            {/* 富文本编辑器-文章内容 */}
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '文章内容不能为空' }]}
            >
              <ReactQuill
                theme="snow"
                placeholder="请输入文章内容"
              ></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Button type="primary" htmlType="submit" size="large">
                发布文章
              </Button>
              <Button size="large" onClick={this.setActicle}>
                存入草稿
              </Button>
            </Form.Item>
          </Form>
        </Card>

        {/* 弹框 */}
        <Modal
          visible={this.state.showPreview}
          title="图片预览"
          footer={null}
          onCancel={this.handleCancel}
        >
          <img
            src={this.state.PreviewUrl}
            alt="example"
            style={{ width: '100%' }}
          />
        </Modal>
      </div>
    )
  }

  // 表单提交
  onFinish = async (val) => {
    this.save(val, false)
  }

  // 封面类型切换
  changeType = (e) => {
    this.setState({
      type: e.target.value,
      fileList: [],
    })
  }

  // 图片上传
  UploadImage = ({ fileList }) => {
    // 上传成功
    this.setState({
      fileList,
    })
  }

  // 图片预览
  handlePreview = (file) => {
    console.log(file)
    const url = file.url || file.response.data.url
    this.setState({
      showPreview: true,
      PreviewUrl: url,
    })
  }

  // 关闭弹窗
  handleCancel = () => {
    this.setState({
      showPreview: false,
      PreviewUrl: '',
    })
  }

  // 图片上传前校验
  beforeUpload = (file) => {
    console.log(file)
    // 判断图片大小不能超过500kb
    if (file.size >= 1024 * 500) {
      message.warn('上传图片不能超过500kb')
      return Upload.LIST_IGNORE
    }
    if (!['image/png', 'image/jpeg'].includes(file.type)) {
      message.warn('只能上传png/jpg格式的图片')
      return Upload.LIST_IGNORE
    }
    return true
  }

  // 存入草稿
  setActicle = async () => {
    const val = await this.formRef.current.validateFields()
    this.save(val, true)
  }

  // 封装保存文章
  save = async (val, draft) => {
    const { fileList, type } = this.state
    if (fileList.length !== type) return message.warn('上传图片数量不正确')
    const images = fileList.map((item) => {
      return item.url || item.response.data.url
    })
    try {
      if (this.state.id) {
        // 修改文章
        await editArticle(
          {
            ...val,
            cover: {
              type,
              images,
            },
            id: this.state.id,
          },
          draft
        )
        message.success('修改文章成功')
      } else {
        // 发布文章
        await addArticle(
          {
            ...val,
            cover: {
              type,
              images,
            },
          },
          draft
        )
        message.success('添加文章成功')
      }
      this.props.history.push('/home/list')
    } catch (err) {
      message.warn('添加文章失败')
    }
  }

  componentDidMount() {
    this.getArticleInfo()
  }

  // 根据id获取文章信息
  getArticleInfo = async () => {
    console.log(this.props)
    if (this.state.id) {
      const { data: res } = await getArticleInfo(this.state.id)
      const val = {
        ...res,
        // 封面状态
        type: res.cover.type,
      }
      // 修改文章给表单设置文章的信息
      this.formRef.current.setFieldsValue(val)
      this.setState({
        // 封面显示
        fileList: res.cover.images.map((item) => {
          return {
            url: item,
          }
        }),
        type: res.cover.type,
      })
    }
  }
}
